package com.jalarbee.stock.product.dao.impl;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.jalarbee.core.generic.dao.impl.GenericDaoJpa;
import com.jalarbee.core.util.Chunk;
import com.jalarbee.stock.category.exception.NoSuchCategoryException;
import com.jalarbee.stock.product.business.Product;
import com.jalarbee.stock.product.business.ProductStatus;
import com.jalarbee.stock.product.dao.ProductDao;

@Repository(value = "productDao")
public class ProductDaoJpa extends GenericDaoJpa<Product, Integer> implements
        ProductDao {

    public List<Product> getProductsByCategory(int categoryId, Chunk chunk)
            throws NoSuchCategoryException {
        Query query = getEntityManager().createQuery("SELECT p FROM Product p WHERE p.defaultCategory.id = ?1");
        query.setParameter(1, categoryId);
        if (chunk != null && chunk.makesSense()) {
            query.setFirstResult(chunk.getStart());
            query.setMaxResults(chunk.getSize());
        }
        List<Product> list = query.getResultList();
        if (list == null || list.isEmpty()) {
            throw new NoSuchCategoryException(
                    "There is no product in this category or the category does not exist.");
        }
        return list;
    }

    public List<Product> getActiveProducts(Chunk chunk) {
        Query query = getEntityManager().createNamedQuery("active.products");
        query.setParameter("status", ProductStatus.ACTIV);
        return query.getResultList();
    }

    public void inactivate(Product product) {
        product.setStatus(ProductStatus.INACT);
        update(product);
    }

    public void activate(Product product) {
        product.setStatus(ProductStatus.ACTIV);
        update(product);
    }
}
